package com.orange.core.util;

import cn.hutool.core.util.StrUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

public class TokenUtil {

    private static final ThreadLocal<String> tokens = new ThreadLocal<>();

    private static String getPrefix() {
        String uri = RequestUtil.getRequest().getRequestURI();
        if (uri.equalsIgnoreCase(Constants.ADMIN_SIGN_IN_PATH)) {
            return String.valueOf(Constants.ADMIN_TOKEN_PREFIX);
        } else if (uri.equalsIgnoreCase(Constants.USER_WX_MINI_SIGN_IN_PATH)) {
            return String.valueOf(Constants.USER_MINI_TOKEN_PREFIX);
        } else {
            return "";
        }
    }

    public static String newToken() {
        String token = getPrefix() + UuidUtil.getUuid() + UuidUtil.getUuid();
        tokens.set(token);
        return token;
    }

    public static String getToken() {
        return getToken(RequestUtil.getRequest(), true);
    }

    public static String getToken(boolean create) {
        return Optional.ofNullable(tokens.get()).orElse(create ? newToken() : null);
    }

    public static String getToken(HttpServletRequest request) {
        return getToken(request, false);
    }

    public static String getToken(HttpServletRequest request, boolean create) {
        String token = tokens.get();
        if (StrUtil.isBlank(token)) {
            token = request.getHeader(Constants.TOKEN_KEY);
            return StrUtil.isNotBlank(token) ? token : create ? newToken() : null;
        }
        return token;
    }

    public static void setToken(String token) {
        tokens.set(token);
    }

    public static void removeToken() {
        tokens.remove();
    }
}
